package com.shardings.service.impl;

import com.shardings.entity.Order;
import com.shardings.entity.OrderItem;
import com.shardings.mapper.OrderMapper;
import com.shardings.service.OrderService;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("orderServiceImpl")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Order order) {
        // 主键如果在配置里生成，则OrderItem拿不到该值。所以改成在这里生成
        Comparable<?> id = new SnowflakeShardingKeyGenerator().generateKey();
        order.setOrderId((Long) id);
        orderMapper.saveOrder(order);

        OrderItem item = new OrderItem();
        item.setOrderId(order.getOrderId());
        item.setAmount(BigDecimal.TEN);
        item.setProductId(1L);
        item.setPurchaseQty(new BigDecimal(11));
        orderMapper.saveOrderItem(item);
    }

    @Override
    public List<Order> getOrderList(Order order) {
        Order orders = orderMapper.getOrder(1L);
        List<Order> list = new ArrayList<>();
        list.add(orders);
        return list;
    }


}
